import threading
from tool import init_log, log, send
from queue import Queue
import json
from gevent import pywsgi
from flask_cors import CORS
from flask import Flask, jsonify, request
from com import do_com
from que import do_que
from gun import do_gun
# from up import do_up


w_queue = Queue(maxsize=0)
d_queue = Queue(maxsize=0)


app = Flask(__name__)
CORS(app)


@app.get("/")
def hello():
    return "server flask"


@app.post("/action")
def do_post():
    msg = "no cmd"

    try:
        data = request.get_json()

        log(data)

        if "cmd" in data:
            cmd = data["cmd"]
            if cmd == "std":
                v = {"gun": ""}

                w_queue.put(v)
                d_queue.put(v)
            elif cmd == "gun":
                val = {
                        "line": "1",
                        "sn": data["wsn"],
                        "v": {
                            "gun": data["v"],
                            }
                        }

                log(val)

                r = send("http://127.0.0.1:9985/plc/put", val)

                log(r)

                v = {"gun": data["v"]}

                w_queue.put(v)
                d_queue.put(v)

            return jsonify({
                "code": 1000,
                "success": True,
                "fail": False,
                }), 200
    except Exception as e:
        msg = "do que error: %s" % e

    return jsonify({
        "message": msg,
        "success": False,
        "fail": True,
        }), 500


if __name__ == '__main__':
    init_log()

    cfg = {}

    with open("config.json", mode="r") as file:
        cfg = json.load(file)

    if not cfg:
        log("open config error")
        exit()

    log("Run server: 9001")

    if "width" in cfg:
        w_thread = threading.Thread(target=do_com, args=(cfg, "width", w_queue))
        w_thread.daemon = True
        w_thread.start()

        qw_thread = threading.Thread(target=do_que, args=(cfg, "width", w_queue))
        qw_thread.daemon = True
        qw_thread.start()

    if "dia" in cfg:
        d_thread = threading.Thread(target=do_com, args=(cfg, "dia", d_queue))
        d_thread.daemon = True
        d_thread.start()

        qd_thread = threading.Thread(target=do_que, args=(cfg, "dia", d_queue))
        qd_thread.daemon = True
        qd_thread.start()

    if "gun" in cfg:
        g_thread = threading.Thread(target=do_gun, args=(cfg, "gun", w_queue, d_queue))
        g_thread.daemon = True
        g_thread.start()

    # u_thread = threading.Thread(target=do_up, args=(cfg))
    # u_thread.daemon = True
    # u_thread.start()

    server = pywsgi.WSGIServer(('0.0.0.0', 9001), app)
    server.serve_forever()
